<?php
namespace Admin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\MvcEvent;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{

    public $view;
    protected $authService;
    protected $em;

    public function __construct(){
        $this->view = new ViewModel();
        $this->em = $this->getEventManager();
        $this->em->attach(MvcEvent::EVENT_DISPATCH, array($this, 'preDispatch'),100);
        echo '<script> var controllername="index"; </script>';
    }


    public function preDispatch(){
        if(!$this->getAuthService()->hasIdentity())
            $this->_redirect()->toRoute(NULL,array('controller'=>'auth','action'=>'login'));
        $username = $this->getAuthService()->getStorage()->read();
        $this->layout('layout/admin');
        $this->layout()->username = $username;
    }

    public function getAuthService(){
        if(!$this->authService){
            $this->authService = $this->getServiceLocator()->get('AuthService');
        }
        return $this->authService;
    }

    public function indexAction(){        
        $userTable = $this->getServiceLocator()->get('Admin\Model\UserTable');
        $billTable = $this->getServiceLocator()->get('Admin\Model\billTable');
        $this->view->income = $billTable->getIncome();
        $this->view->users = $userTable->fetchAll();
        return $this->view;
    }

    public function addAction(){        
        $request = $this->getRequest();
        if($request->isPost())
            $id = $request->id;
        else
            $id = NULL;
        $userTable = $this->getServiceLocator()->get('Admin\Model\UserTable');
        $thongtin = $userTable->getUser($id);
        return $this->view;
    }

    public function editAction(){        
        return $this->view;
    }

}
